How to use break and continue in a foreach loop in Powershell
1234567891011121314151617181920212223242526# Use break to get out of the loop
$files = Get-ChildItem C:\PSfolder -File
foreach ($file in $files)
{
if ($file.Name -like "*.ps1")
{
$file.Name
break # exit the foreach loop
}
}
# Use continue to skip the rest of a loop but go onto the next iteration
$files = Get-ChildItem C:\PSfolder -File
foreach ($file in $files)
{
if ($file.Name -like "*.ps1")
{
$file.Name
continue # exit and go tho the next item in foreach
"This code will be skipped"
}
"This isn't a powershell file: $file"
}
|